<?php

namespace App\HttpController\Admin;

use App\HttpController\BaseController;
use App\Model\AdminsModel;
use App\Model\LoginLogsModel;
use App\Utility\ApiToken;
use App\Utility\Captcha;
use Carbon\Carbon;
use EasySwoole\EasySwoole\Config;
use EasySwoole\EasySwoole\ServerManager;
use EasySwoole\Utility\Hash;
use EasySwoole\Validate\Validate;


class LoginController extends BaseController {

    public function login(){
        $request = $this->request();
        $data = $request->getRequestParam();

        // TODO: 字段验证.
        $validate = new Validate();
        // TODO: 字段验证闭包函数func只能返回true和false.
        $validateCode = (new Captcha())->check($data['captcha'],$data['captchaKey']);
        $validate->addColumn('captcha')->required('请填写验证码')->func(function () use($validateCode){
            return $validateCode;
        },'验证码输入错误');

        $adminModel = new AdminsModel();
        $user = $adminModel->where('username', $data['username'])->first();

        $validate->addColumn('username')->required('请填写管理员账号')->func(function () use($data,$user){
            return !empty($user);
        },'管理员账户不存在，请联系超级管理员');

        $validate->addColumn('password')->required('请填写密码')->func(function () use($data,$user){
            return Hash::validatePasswordHash($data['password'],$user['password']);
        },'密码输入错误');

        if($this->validate($validate)){
            $token = ApiToken::sessionEncrypt($user['id']);
            //更新登录时间
            $adminModel->update(['id'=>$user['id'],'login_at'=>Carbon::now()]);
            $return = [
                'userinfo' => ['id' => $user['id'], 'nickname' => $user['nickname']],
                'token' => $token
            ];
            return $this->writeJson(0,$return,'登录成功，页面即将跳转...');
        } else {
            return $this->writeJson(1, null, $validate->getError()->__toString());
        }
    }


    /**
     * @title 验证码
     * @description 获取验证码信息
     * @method GET
     * @request manage/captcha
     * @return string captcha 验证码图片地址
     * @return string captchaKey 验证码加密key,用于验证验证码是否正确
     */
    public function captcha(){
        $captcha = (new Captcha())->create();
        return $this->writeJson(0,$captcha);
    }
}
